package com.wxj.bank.storage.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wxj.bank.module.constant.Constants;
import com.wxj.bank.module.page.PageBean;
import com.wxj.bank.module.utils.UUIDUtils;
import com.wxj.bank.storage.dao.OrderMapper;
import com.wxj.bank.storage.model.Order;
import com.wxj.bank.storage.model.OrderExample;
import com.wxj.bank.storage.service.IOrderService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author shengtao
 * @Description: 订单
 * @date 2019/02/19 17:02
 */
@Service
public class OrderServiceImpl implements IOrderService{

    @Autowired
    private OrderMapper mapper;

    @Override
    public Order save(Order order) {
        order.setId(UUIDUtils.genUUID());
        this.mapper.insert(order);
        return order;
    }

    @Override
    public void save(List<Order> orders) {
        orders.stream().map(order -> {order.setId(UUIDUtils.genUUID());return order;}).collect(toList());
        this.mapper.batchInsert(orders);
    }

    @Override
    public void remove(String id) {
        this.mapper.deleteByPrimaryKey(id);
    }

    @Override
    public Order update(Order order) {
        mapper.updateByPrimaryKey(order);
        return order;
    }

    @Override
    public Order find(String id) {
        return this.mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Order> find(Order order) {
        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(order.getId())){
            criteria.andIdEqualTo(order.getId());
        }
        if(StringUtils.isNotBlank(order.getProductId())){
            criteria.andProductIdEqualTo(order.getProductId()+ Constants.SYMBOL_PERCENT);
        }
        return this.mapper.selectByExample(example);
    }

    @Override
    public PageBean<Order> find(Order order, PageBean<Order> page) {
        OrderExample example = new OrderExample();
        OrderExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotBlank(order.getId())){
            criteria.andIdEqualTo(order.getId());
        }
        if(StringUtils.isNotBlank(order.getProductId())){
            criteria.andProductIdEqualTo(order.getProductId()+ Constants.SYMBOL_PERCENT);
        }
        Page<Order> pages = PageHelper.startPage(page.getCurrentPage(),page.getPageSize());
        this.mapper.selectByExample(example);
        return new PageBean<>(pages);
    }
}
